package aop;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Log;
import entity.Users;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import service.LogService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Map;


@Component  // 对象由spring管理
@Aspect
public class LogAspect {
    @Autowired
    private LogService logService;
    // 定义日志器
    public static final Logger LOGGER = LogManager.getLogger(LogAspect.class);


    // 定义切入点
    @Pointcut("@annotation(aop.LogData),execution")
    public void pointCut(){

    }

    // 记录日志的切面方法
    @Before("pointCut()")
    public void log(JoinPoint joinPoint){
        //获取到方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取到连接点方法对象
        Method method = signature.getMethod();
        // 获取控制器名称
        Class<?> clazz = method.getDeclaringClass();
        String methodControllerName = clazz.getName();
        //获取方法上面特定的注解
        LogData annotation = method.getAnnotation(LogData.class);
        LogType logType = annotation.logType();
        String description = annotation.description();
        LOGGER.info("获取到注解内容：logType="+logType.getType()+",description:"+description);
        // aop中获取request
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        //获取操作人
        Users user = (Users) session.getAttribute("admin");
        //获取请求数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //将对象转换成json字符串==>存储到请求数据字段中
        //jackSon json字符串操作
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            String s = objectMapper.writeValueAsString(parameterMap);
            LOGGER.info("请求数据："+s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //todo 将日志信息保存到数据库  LogController service mapper jsp
        Log log = new Log();
        log.setUser_id(user.getId());
        log.setOperation(user.getAccount()== null ?"游客":user.getAccount());
        log.setOperation_content(methodControllerName+"  "+description);
        boolean b = logService.insert(log);

    }

}
